/*
 *  Copyright 2008 The MITRE Corporation (http://www.mitre.org/). All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mitre.mrald.taglib;

import org.mitre.mrald.control.MsgObject;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.jsp.JspException;
import javax.servlet.http.*;
import javax.servlet.jsp.tagext.TagSupport;
import org.mitre.lattice.query.LatticeQuery;
import org.mitre.mrald.util.Config;
import org.mitre.mrald.util.MiscUtils;
import org.mitre.mrald.util.MraldConnection;
import org.mitre.mrald.util.MraldException;
import org.mitre.mrald.util.MraldOutFile;
import org.mitre.mrald.util.User;

/**
 *  Description of the Class
 *
 *@author     ksarver
 *@created    Sept 16, 2003
 */
public abstract class MraldSpecTag extends TagSupport
{

    /**
     *  Description of the Field
     */
    protected int processCount = 0;


    /**
     *  Constructor for the SubjectBoxTag object
     */
    public MraldSpecTag()
    {
        super();
    }


    /**
     *  Retrieves and prints the user's personal forms list
     *
     *@return                   An int. Not used for anything.
     *@exception  JspException  Required by TagSupport. Used ot pass up the
     *      other exceptions.
     */
    public int doStartTag()
        throws JspException
    {
        try
        {
            User user = ( User ) pageContext.getSession().getAttribute( Config.getProperty( "cookietag" ) );
            pageContext.getOut().print( init() );
            pageContext.getOut().print( processQuery( getQuery(), user ) );
            pageContext.getOut().print( endOutput() );
            pageContext.getOut().flush();

        }
        catch ( IOException e )
        {
            throw new JspException( e );
        }
        catch ( MraldException e )
        {
            throw new JspException( e );
        }
        return 0;
    }


    /**
     *  Description of the Method
     *
     *@return    Description of the Return Value
     */
    protected String init()
    {
        return null;
    }


    /**
     *  Gets the query attribute of the NeuroSpecificTag object
     *
     *@return    The query value
     */
    protected abstract String[] getQuery();


    /**
     *  Description of the Method
     *
     *@param  query               Description of the Parameter
     *@param  user                Description of the Parameter
     *@return                     Description of the Return Value
     *@exception  MraldException  Description of the Exception
     */
    public String processQuery( String[] query, User user )
        throws MraldException
    {
        try
        {


            StringBuffer ret = new StringBuffer();
            String datasource = (String)pageContext.getSession().getAttribute( "Datasource" );
            if( datasource == null || datasource.equals("") )
            {
                datasource = "main";
            }
            MraldConnection conn = new MraldConnection( datasource,
                    new MsgObject((HttpServletRequest)pageContext.getRequest(), (HttpServletResponse)pageContext.getResponse() ) );
            Connection con = conn.getConnection();
//            LatticeQuery latQuery = new LatticeQuery();

            ResultSet rs = null;
            for ( int i = 0; i < query.length; i++ )
            {
                String queryFinal = query[i];

                //MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "MraldSpecTag: processing query " + queryFinal   );
                if (queryFinal.equals(""))
                	continue;

                if ( Config.usingSecurity )
                {
                    queryFinal = LatticeQuery.adaptQuery( query[i], user );
                }

                StringBuffer logInfo = new StringBuffer();

                long startTime = MiscUtils.logQuery( user.getEmail(), datasource, query[i], logInfo );

                // MraldOutFile.appendToFile( "In NeuroSpecificTag, executing: "+queryFinal );
                Statement stmt = con.createStatement(
                    ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_UPDATABLE );

                rs = stmt.executeQuery( queryFinal );
                /*
                 *  RETURN success status
                 */
                MiscUtils.logQueryRun( startTime, logInfo );

                processCount = i + 1;
                ret.append( processResultSet( rs ) );
            }
            rs.close();
            conn.close();
            return ret.toString();
        }
        catch ( SQLException e )
        {
            throw new MraldException( e );
        }
    }


    /**
     *  Description of the Method
     *
     *@param  rs                  Description of the Parameter
     *@return                     Description of the Return Value
     *@exception  MraldException  Description of the Exception
     */
    protected abstract String processResultSet( ResultSet rs )
        throws MraldException;


    /**
     *  To finish off all the
     *  <table>
     *    tags at the end of the page
     *
     *@return                   Description of the Return Value
     */

    protected abstract String endOutput();

    public int doEndTag()
    {
    	/*try {
			pageContext.getOut().flush();
			pageContext.getOut().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "MraldSpecTag: DoEndTag : IOException:  " + e.getMessage()      );

			e.printStackTrace();
		}*/

    	return 0;
    }
}

